<!-- Author: Edwin -->
<template>
  <div class="new-bot-design-page"
       v-loading='pageLoading'>
    <!--    <div v-if="botInfo.tenantCode !== $store.state.user.tenantCode"-->
    <!--         class="no-permission">-->
    <!--      <span v-if="botInfo.tenantCode">{{ $t('custom.bots.design.noPermissions') }}</span>-->
    <!--      <span v-else>{{ $t('custom.bots.design.noData') }}</span>-->
    <!--    </div>-->
    <div class="page-content"
         @click="exclusivePop">

      <div class="scroll-css canvas">
        <div class="scroll-css-left"
             v-show="blockGpVisible">
          <BlockItem ref="block_item"
                     :blockGpTabCur="blockGpTab"
                     @selectblockInfo="selectblockInfoHnadel"></BlockItem>
        </div>
        <div class="scroll-css-right">
          <div v-if="$hasPermission('sys:bots:design') || $hasPermission('sys:bots:design:custom')"
               class="canvas-header"
               v-only-clone="$store.getters.botDetail">
            <el-tooltip :open-delay="1000"
                        placement="top">
              <div slot="content"
                   style="text-align:center;">{{ $t('custom.bots.design.resetBtnTips1') }} <br /> {{ $t('custom.bots.design.resetBtnTips2') }}</div>
              <div v-if="$hasPermission('sys:bots:design')"
                   class="action-btn"
                   @click="resetBot"
                   style="margin-right: 10px;">
                <div class="cuifont icon_arrow_counterclockwise"></div>
                <div class="text">{{ $t('custom.bots.resetbtn') }}</div>
              </div>
            </el-tooltip>
            <el-tooltip :open-delay="1000"
                        :content="$t('custom.bots.design.clearBtnTips')"
                        placement="top">
              <div v-if="$hasPermission('sys:bots:design:custom')"
                   class="action-btn"
                   @click="clearBlocks">
                <div class="cuifont icon_erase"></div>
                <div class="text">{{ $t('custom.bots.clearbtn') }}</div>
              </div>
            </el-tooltip>
            <div class="header">
              <!-- <div class="header-name" style="display:flex; align-items:center">
                <el-tooltip :open-delay="1000" class="item" effect="dark" :content="$t('custom.bots.backtodetail')" placement="top">
                    <i style="width:28px;height:28px;margin-right:10px;line-height:28px;text-align:center;border-radius:5px" @click="backtodetail(botInfo.id)" class="cuifont icon_arrow_left button_hover"></i>
                  </el-tooltip>
                <span> {{ botInfo.name }}</span>
              </div> -->
              <div class="action-btn-group">
                <el-tooltip :open-delay="1000"
                            :content="$t('custom.bots.design.saveBtnTips')"
                            placement="top">
                  <div v-if="$hasPermission('sys:bots:design')"
                       @click="confirmFlowy"
                       v-loading="saveLoading"
                       class="action-btn">
                    <div class="cuifont icon_save"></div>
                    <div class="text">{{ $t('custom.bots.savebtn') }}</div>
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
          <div class="canvas-content"
               :class="{ 'limit-content-height': ($hasPermission('sys:bots:design') || $hasPermission('sys:bots:design:custom')) }"
               :style="{height:(!$hasPermission('sys:bots:design') && !$hasPermission('sys:bots:design:custom'))?'100%':''}"
               id="canvas-content">
            <div class="canvas-content-scroll"
                 v-if="dataSource.length > 0"
                 :style="{ 'width': `${computedScrollWidth(dataSource)}px`,'height': `${computedScrollHeight(dataSource)}px` }">
              <div>
                <div class="block"
                     :style="{ 'width': `${blockWidth}px`,'height': `${blockHeight}px`,'left':`${item.x}px`, 'top': `${item.y}px` }"
                     v-for="(item, i) in dataSource"
                     :key="i">
                  <div class="block"
                       v-if="item.blockType === 'add'"
                       @click="addBlcok(item)"
                       style="padding: 0 10px;width:100%;height:100%;cursor: pointer;color: #BFBFBF;position: relative;">
                    {{item.spaceval}}
                    <div class="close-blank-block cuifont icon_dismiss"
                         @click.stop="closeBlankBlock(item)"></div>
                  </div>
                  <div v-else
                       class="block"
                       @click.stop="blcokclick(item)"
                       style="padding: 0 10px;width:100%;height:100%;">
                    <div class="block-left">
                      <div class="icon-name">
                        <el-image class="block-icon"
                                  draggable="false"
                                  :src="item.icon || defaultScriptIcon"
                                  fit="fill"></el-image>
                        <div class="icon-name-value">{{ item.name }}</div>
                      </div>
                      <div class="icon-note">
                        <div v-show="editDescritionId !== item.id"
                             class="icon-note-value">
                          {{ item.briefDescription }}
                        </div>
                        <el-input v-show="editDescritionId === item.id"
                                  v-model="item.briefDescription"
                                  :ref="`description-${item.id}`"
                                  @change="descriptionInputChange(item)"
                                  @focus="descriptionInputFocus(item)"
                                  @blur="descriptionInputBlur"
                                  size="mini"
                                  placeholder="Input Description."
                                  class="icon-note-value"></el-input>
                      </div>
                    </div>
                    <div class="block-right">
                      <el-dropdown @command="dropdownClick($event,item)">
                        <div class="el-icon-more"
                             v-only-clone="$store.getters.botDetail"></div>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item command='edit'>
                            <div class="more_operation">
                              <div class="cuifont icon_edit"></div>
                              <div>{{ $t('custom.bots.design.moreMenuEdit') }}</div>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command='editnote'>
                            <div class="more_operation">
                              <div class="cuifont icon_comment_add"></div>
                              <div>{{ $t('custom.bots.design.moreMenuEditNote') }}</div>
                            </div>
                          </el-dropdown-item>
                          <el-dropdown-item command='delete'>
                            <div class="more_operation">
                              <div class="cuifont icon_delete"></div>
                              <div>{{ $t('custom.bots.design.moreMenuDelete') }}</div>
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </div>
                </div>
              </div>
              <lineCanvas v-for="(item,index) in lineData"
                          :key="'index'+index"
                          :linkInfo="item"></lineCanvas>
              <arcLineCanvas v-for="(item,index) in lineData"
                             :key="'arc'+index"
                             :linkInfo="item"></arcLineCanvas>
              <addBlockPoprover @addBlock="addBlockHandl"
                                :popStatus="addPopStatus"
                                @nodeInfo="nodeInfoHandel"></addBlockPoprover>
              <fixeArcline ref="fiexarcline"></fixeArcline>
            </div>
            <div v-if="$hasPermission('sys:bots:design:custom')&&!(dataSource.length > 0)&&dataSourceBak.length>0"
                 class="new_block_btn">
              <div @click="newbotBlock">
                <span class="el-icon-plus"></span>
                <div>{{ $t('custom.bots.design.newBlock') }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <SettingModel ref="setting-model"
                  :botId='botId'
                  @setScriptList='setSysBotScriptList' />
  </div>
</template>

<script>
import * as ComputedFunction from './computed'
import { drawLine } from './drawLine.js'
import addBlockPoprover from './addBlockPoprover.vue'
import SettingModel from './setting-model'
import BlockItem from './blockGroup.vue'
import lineCanvas from './line.vue'
import arcLineCanvas from './arcLine.vue'
import fixeArcline from './fixeArcline.vue'
import { getUUID } from '@/utils'
import moment from 'moment'
import { replaceEmailContent } from '@/utils/formatEmail.js'
export default {
  props: {
    botIds: {
      type: String,
      default: ''
    },
    needCloseBtn: {
      type: Boolean,
      default: false
    }
  },
  provide () {
    return {
      scriptList: () => this.blocksList,
      blockDataSource: () => this.dataSource,
      botScriptList: () => this.botScriptList,
      botInfo: () => this.botInfo
    }
  },
  components: { SettingModel, addBlockPoprover, BlockItem, lineCanvas, arcLineCanvas, fixeArcline },
  data () {
    return {
      botId: '',
      pageLoading: false,
      saveLoading: false,
      defaultBotIcon: this.$ossLink + '/app/bot/bot-icon-normal.png',
      defaultScriptIcon: this.$ossLink + '/app/bot/script/script_icon_general.png',
      botInfo: {},
      blockWidth: 500,
      blockHeight: 76,
      blockXSpacing: 10,
      blockYSpacing: 150,
      blocksList: [],
      dataSource: [],
      botScriptList: [],
      dataSourceBak: [],
      botScriptListBak: [],
      parentNodeInfo: null,
      lineData: [],
      blockGpVisible: false,
      selectBlockType: 1000,
      defaultEmptyBlock: {
        spaceval: 'Select a Block…',
        blockType: 'add'
      },
      currBlock: null,
      addPopStatus: 0,
      editDescritionId: -9999,
      editDescritionValue: null,
      blockGpTab: false,
      updateStatus: false
    }
  },
  created () {
    this.botId = this.botIds
  },
  watch: {
    'botIds': function (val) {
      this.botId = val
    },
    dataSource: {
      handler (val) {
        try {
          let res = this.dataSource.find(item=>item.pid === -1)
          if(res) {
            this.botInfo.triggerType = res.triggerEvent
          }else {
            this.botInfo.triggerType = ''
          }
        } catch (e) {
          console.log(e)
        }
        if (this.updateStatus && this.checkBlockisTrigger()) {
          this.editBlock(this.checkBlockisTrigger())
          this.$refs[`setting-model`].loading = false
        }
        this.updateStatus = false
      },
      deep: true
    }
  },
  mounted () {
    // if (this.$refs[`setting-model`]) {
    //   this.$refs[`setting-model`].showDialog = true
    //   this.$refs[`setting-model`].loading = true
    // }
    window.addEventListener('click', this.clickOther)
  },
  beforeDestroy () {
    this.clearPage()
    window.removeEventListener('click', this.clickOther)
  },
  methods: {
    backtodetail (id) {
      this.$router.push({ path: `bot-${id}`, query: { pageid: 'botdetail', botId: id } })
    },
    init () {
      this.updateStatus = true
      // this.getBotInfo()
      this.getBlocksList()
    },
    exclusivePop ($event) {
      this.$store.commit('BOTDESIGNARCSTATUS', 100)
      this.$refs.fiexarcline.clickCanvas = true
      document.querySelectorAll('.arc-line__line').forEach(element => {
        element.style.display = 'none'
      })
      if ($event.target.className.indexOf('fixed_arc-line') === -1) document.querySelector('.fixed_arc-line').style.display = 'none'
    },
    newbotBlock () {
      this.addBlockHandl(0)
    },
    addBlcok (item) {
      this.currBlock = item
      this.blockGpVisible = true
    },
    blcokclick (item) {
      this.addPopStatus = new Date().getTime()
      if (item.islast) this.$refs.fiexarcline.setCanvasP(item)
      else document.querySelector('.fixed_arc-line').style.display = 'none'
    },
    addBlockHandl (data) {
      this.selectBlockType = data
      let defaultEmptyBlock = this._.cloneDeep(this.defaultEmptyBlock)
      defaultEmptyBlock.trackId = getUUID()
      if (this.selectBlockType === 1) {
        defaultEmptyBlock.pid = this.parentNodeInfo.id
        defaultEmptyBlock.id = this.dataSource.sort((a, b) => a.id - b.id).slice().pop().id + 1
        defaultEmptyBlock.level = this.parentNodeInfo.level + 1
        defaultEmptyBlock.selfTrackId = getUUID()
        defaultEmptyBlock.selfTriggerId = this.parentNodeInfo.selfTrackId
        this.blockChrielevelStatus(defaultEmptyBlock.pid, defaultEmptyBlock.id, defaultEmptyBlock.level, true)
      } else if (this.selectBlockType === 2) {
        defaultEmptyBlock.pid = this.parentNodeInfo.id
        defaultEmptyBlock.level = this.parentNodeInfo.level + 1
        defaultEmptyBlock.id = this.dataSource.sort((a, b) => a.id - b.id).slice().pop().id + 1
        defaultEmptyBlock.selfTrackId = getUUID()
        defaultEmptyBlock.selfTriggerId = this.parentNodeInfo.selfTrackId
      } else {
        defaultEmptyBlock.level = 0
        defaultEmptyBlock.pid = -1
        defaultEmptyBlock.id = 0
        defaultEmptyBlock.selfTrackId = getUUID()
        defaultEmptyBlock.selfTriggerId = this.botInfo.id
      }

      this.dataSource.push(defaultEmptyBlock)
      this.defaultEmptyBlock = defaultEmptyBlock
      this.initBlockAddress()
    },
    blockChrielevelStatus (originalId, emptyBlockid, emptyLevel, isfirst) {
      let copydataSource = this._.cloneDeep(this.dataSource)
      let childrenPidgp = []
      for (let index = 0; index < copydataSource.length; index++) {
        const element = copydataSource[index]
        if (originalId === element.pid) {
          childrenPidgp.push({
            pid: element.pid,
            level: element.level,
            originalId: element.id
          })
          element.originPid = element.pid
          element.originid = element.id
          element.originLevel = element.level
          if (isfirst) element.pid = emptyBlockid
          element.level = emptyLevel + 1
        }
      }
      this.dataSource = copydataSource
      if (childrenPidgp.length === 0) return false
      this.changeChildrenLevel(childrenPidgp)
    },
    changeChildrenLevel (pidGroup) {
      for (let index = 0; index < pidGroup.length; index++) {
        let childrenPidgp = []
        const element = pidGroup[index]
        for (let index = 0; index < this.dataSource.length; index++) {
          const ele = this.dataSource[index]
          if (ele.pid === element.originalId) {
            childrenPidgp.push({
              pid: ele.pid,
              level: ele.level,
              originalId: ele.id
            })
            ele.level = Number(ele.level) + 1
          }
        }
        if (childrenPidgp.length > 0) this.changeChildrenLevel(childrenPidgp)
      }
    },
    checkBotBlock () {
      if (this.dataSource.length === 0 || (this.dataSource.length === 1 && this.dataSource[0].blockType)) {
        this.blockGpTab = true
      } else this.blockGpTab = false
    },
    nodeInfoHandel (data) {
      this.parentNodeInfo = data[0]
    },
    selectblockInfoHnadel (data) {
      let newBlock = JSON.parse(JSON.stringify(this.defaultEmptyBlock))
      newBlock.blockId = data.id
      newBlock.id = this.currBlock.id
      newBlock.pid = this.currBlock.pid
      newBlock.level = this.currBlock.level
      newBlock.selfTrackId = this.currBlock.selfTrackId
      newBlock.selfTriggerId = this.currBlock.selfTriggerId
      this.blockGpVisible = false
      this.dataSource.forEach((element, index) => {
        if (element.id === this.currBlock.id) this.dataSource.splice(index, 1)
      })
      delete newBlock.blockType
      delete newBlock.x
      delete newBlock.y
      delete newBlock.position
      this.dataSource.push({
        ...data,
        ...newBlock
      })
      this.initBlockAddress()
    },
    checkdataSourceHasChildren () {
      this.checkBotBlock()
      let idGp = [-1]
      for (let index = 0; index < this.dataSource.length; index++) {
        const ele = this.dataSource[index]
        idGp.push(ele.pid)
      }
      for (let index = 0; index < this.dataSource.length; index++) {
        const ele = this.dataSource[index]
        if (idGp.includes(ele.id)) ele.islast = false
        else ele.islast = true
      }
    },
    getParallelBlocktrackId () {
      for (let index = 0; index < this.dataSource.length; index++) {
        const element = this.dataSource[index]
        if (element.id === this.parentNodeInfo.pid) return element.selfTrackId
      }
    },
    clearPage () {
      this.blockType = null
      this.blocksList = []
      this.botInfo = {}
    },
    getBlocksList () {
      this.pageLoading = true
      this.$interface.bots.getScriptListApi({ tenantId: this.$store.state.user.tenantCode })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.blocksList = res.data
          this.getBotInfo()
        }).catch(() => { })
    },
    getBotInfo () {
      this.pageLoading = true
      this.$interface.botStore.getTenantBotInfoApi({ id: this.botId })
        .then(({ data: res }) => {
          this.pageLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.botInfo = res.data
          this.$store.state.bot.businessType = res.data.businessType
          this.$nextTick(() => {
            this.setOriginData(res.data)
            this.resetDataForm(res.data)
            this.resetDataSource()
          })
        })
        .catch(() => { this.pageLoading = false })
    },
    setOriginData (data) {
      try {
        let originType = data.sysBotScriptList[0].paramsValue['radioSelect']['radioType']
        let originId = data.sysBotScriptList[0].paramsValue['radioSelect']['selectId']
        this.$store.dispatch('triggerSelectDataIType', originType)
        this.$store.dispatch('triggerSelectDataId', originId)
      } catch (error) { }
    },
    updateBotInfo (params) {
      this.saveLoading = true
      this.$interface.botStore.putBotUpdateScriptApi(this.botId, params)
        .then(({ data: res }) => {
          this.saveLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.settingModelSwitch = true
          this.$message.success(res.msg)
          // this.getBotInfo()
        })
        .catch(() => {
          this.saveLoading = false
        })
    },
    confirmFlowy () {
      if (!this.botId) {
        return this.$message.error(this.$t('custom.bots.design.reloadTips'))
      }
      if (this.dataSource.length < 1) {
        return this.$message.error(this.$t('custom.bots.design.reloadTips'))
      }
      const params = {
        ...this.botInfo,
        flowSetting: this.dataSource,
        sysBotScriptList: this.botScriptList.map(v => {
          v.paramsValue.emailTemplateContent = v.paramsValue.emailTemplateContent && replaceEmailContent(v.paramsValue.emailTemplateContent)
          v.paramsValue.teamsChannelTemplateContent = v.paramsValue.teamsChannelTemplateContent && typeof v.paramsValue.teamsChannelTemplateContent === 'object'?  this.cardMessage(v.paramsValue.teamsChannelTemplateContent,replaceEmailContent(v.paramsValue.teamsChannelTemplateContent.message)) :replaceEmailContent(v.paramsValue.teamsChannelTemplateContent)
          v.paramsValue.teamsChatTemplateContent = v.paramsValue.teamsChatTemplateContent && typeof v.paramsValue.teamsChatTemplateContent === 'object'? this.cardMessage(v.paramsValue.teamsChatTemplateContent,replaceEmailContent(v.paramsValue.teamsChatTemplateContent.message) ) :replaceEmailContent(v.paramsValue.teamsChatTemplateContent)
          v.paramsValue.webTeamsChatTemplateContent = v.paramsValue.webTeamsChatTemplateContent && replaceEmailContent(v.paramsValue.webTeamsChatTemplateContent)
          if (Array.isArray(v.paramsValue.teamsChatCycle) && v.paramsValue.teamsChatCycle.length) {
            v.paramsValue.date = v.paramsValue.teamsChatCycle[0].date
          } else if (Array.isArray(v.paramsValue.emailChatCycle) && v.paramsValue.emailChatCycle.length) {
            v.paramsValue.date = v.paramsValue.emailChatCycle[0].date
          }
          if(v.paramsValue.scheduleTemplate&&!v.paramsValue.scheduleTemplate.timezoneid){
            v.paramsValue.scheduleTemplate.timezoneid=this.$store.state.user.timezoneId
            v.paramsValue.scheduleTemplate.timezoneoffset=moment.tz(v.paramsValue.scheduleTemplate.timezoneid).format('Z')
          }
          if(v.paramsValue.scheduleTemplate&&!v.paramsValue.scheduleTemplate.timezoneoffset){
            v.paramsValue.scheduleTemplate.timezoneoffset=moment.tz(v.paramsValue.scheduleTemplate.timezoneid).format('Z')
          }
          if(v.paramsValue.scheduleTemplate&&!v.paramsValue.scheduleTemplate.times){
            let times = new Date()
            let dates = times.getFullYear() + '-' + ((times.getMonth() + 1) > 9 ? (times.getMonth() + 1) : `0${(times.getMonth() + 1)}`) + '-' + (times.getDate() > 9 ? times.getDate() : `0${times.getDate()}`)
            let daTime = (times.getHours() > 9 ? times.getHours() : `0${times.getHours()}`) + ':' + (times.getMinutes() > 9 ? times.getMinutes() : `0${times.getMinutes()}`) + ':' + (times.getSeconds() > 9 ? times.getSeconds() : `0${times.getSeconds()}`)
            let totalDetas = dates + 'T' + daTime + 'Z'
            v.paramsValue.scheduleTemplate.times=totalDetas
          }
          if(v.paramsValue.scheduleTemplate&&v.paramsValue.scheduleTemplate.times&&v.paramsValue.scheduleTemplate.times.length>21){
            v.paramsValue.scheduleTemplate.times=moment(v.paramsValue.scheduleTemplate.times.slice(0,-1)).format('YYYY-MM-DDTHH:mm:ss')+'Z'
          }
          return v
        }),
        triggerType: this.getTriggerType(),
        tenantLog: {
          operationGroup: 0,
          operationType: 3,
          operation: {
            mode: 'design'
          }
        }
      }
      this.updateBotInfo(params)
    },
    cardMessage(data,str){
      data.message = str
      return data
    },
    resetBot () {
      this.$confirm(this.$t('custom.warnningTips', { 'warnning': 'reset' }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('custom.continue'),
        cancelButtonText: this.$t('cancel'),
        type: 'danger'
      })
        .then(() => {
          this.dataSource = JSON.parse(JSON.stringify(this.dataSourceBak))
          this.botScriptList = JSON.parse(JSON.stringify(this.botScriptListBak))
          this.initBlockAddress()
        })
        .catch(() => { })
    },
    clearBlocks () {
      this.$confirm(this.$t('custom.warnningTips', { 'warnning': 'clear' }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('custom.continue'),
        cancelButtonText: this.$t('cancel'),
        type: 'danger'
      })
        .then(() => {
          this.dataSource = []
          this.initBlockAddress()
        })
        .catch(() => { })
    },
    initBlockAddress () {
      try {
        ComputedFunction.initBlock(this.dataSource, this.blockWidth, this.blockXSpacing, this.blockYSpacing)
        this.checkdataSourceHasChildren()
        this.lineData = []
        this.$nextTick(() => { this.lineData = drawLine(this.dataSource) })
      } catch (error) {
        this.checkdataSourceHasChildren()
        this.lineData = []
        this.$nextTick(() => { this.lineData = drawLine(this.dataSource) })
      }
      let oldList = this.botInfo.sysBotScriptList
      const getDataSourceIndex = (trackId) => {
        return this.dataSource.findIndex(e => e.selfTrackId === trackId)
      }
      let hasBlockList = oldList.filter(e => getDataSourceIndex(e.trackId) > -1)
      hasBlockList.forEach(item => {
        let parentNodeIndex = this.dataSource.findIndex(e => e.id === this.dataSource[getDataSourceIndex(item.trackId)].pid)
        if (parentNodeIndex > -1) {
          item.triggerId = this.dataSource[parentNodeIndex].selfTrackId ? this.dataSource[parentNodeIndex].selfTrackId : this.dataSource[parentNodeIndex].trackId
        } else {
          item.triggerId = this.botInfo.id
        }
      })
      this.botScriptList = hasBlockList
    },
    computedScrollWidth (list) {
      return ComputedFunction.getContentWidth(list, this.blockWidth, this.blockXSpacing)
    },
    computedScrollHeight (list) {
      return ComputedFunction.getContentHeight(list, this.blockHeight)
    },
    resetDataSource () {
      if (typeof this.botInfo.flowSetting === 'object' && Array.isArray(this.botInfo.flowSetting)) {
        this.dataSource = this.botInfo.flowSetting.map(item=>{
          let block = this.blocksList.find(e=>e.id === item.blockId)
          if(!block) return item
          return {
            ...item,
            paramsJson: block.paramsJson,
            name: block.name,
            icon: block.icon,
            type: block.type,
            triggerEvent: block.triggerEvent,
            // briefDescription: block.briefDescription,
            description: block.description,
            roleIds: block.roleIds,
          }
        })
      } else {
        this.dataSource = ComputedFunction.resetDataLists(this.botInfo.flowSetting, this.botInfo.id)
      }
      
      // this.dataSource = ComputedFunction.resetDataListsName(this.dataSource, this.botInfo.sysBotScriptList)
      this.$refs[`setting-model`].open(this.dataSource[0])
      this.initBlockAddress()
      this.$nextTick(() => {
        this.dataSourceBak = JSON.parse(JSON.stringify(this.dataSource))
        this.botScriptListBak = JSON.parse(JSON.stringify(this.botScriptList))
      })
    },
    checkBlockisTrigger () {
      return this.dataSource.find(e => e.name === 'Trigger' || e.name === 'Timed Trigger' || e.name === 'Teams Command' || e.name === 'Real-time Data')
    },
    resetDataForm (data) {
      this.botScriptList = data.sysBotScriptList
    },
    dropdownClick (e, item) {
      if (e === 'edit') {
        this.editBlock(item)
      }
      if (e === 'editnote') {
        this.editDescrition(item)
      }
      if (e === 'delete') {
        this.deleteBlock(item)
      }
    },
    editBlock (blockInfo) {
      this.$refs[`setting-model`].open(blockInfo)
    },
    editDescrition (blockInfo) {
      this.editDescritionId = blockInfo.id
      this.editDescritionValue = blockInfo.briefDescription
      let _self = this
      setTimeout(() => {
        _self.$refs[`description-${blockInfo.id}`][0].focus()
      }, 100)
    },
    deleteBlock (blockInfo) {
      this.$confirm(this.$t('custom.warnningTips', { 'warnning': 'delete' }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('custom.continue'),
        cancelButtonText: this.$t('cancel'),
        type: 'danger'
      })
        .then(() => {
          this.$refs.fiexarcline.closeThatCav()
          this.dataSource = ComputedFunction.deleteBlocks(this.dataSource, blockInfo.id)
          this.initBlockAddress()
        })
        .catch(() => { })
    },
    descriptionInputChange (value) {
    },
    descriptionInputFocus (blockInfo) {
      let nowBlockIndex = this.dataSource.findIndex(e => e.id === blockInfo.id)
      this.dataSource[nowBlockIndex].briefDescription = this.editDescritionValue
    },
    descriptionInputBlur () {
      this.editDescritionId = -9999
      this.editDescritionValue = null
    },
    closeBlankBlock (blockInfo) {
      this.dataSource = ComputedFunction.deleteBlocks(this.dataSource, blockInfo.id)
      this.initBlockAddress()
      setTimeout(() => { this.blockGpVisible = false }, 0)
    },
    setSysBotScriptList (scriptList) {
      this.botInfo.sysBotScriptList = scriptList
    },
    getTriggerType () {
      let triggerType = null
      try {        
        let triggerBlock = this.dataSource.find(e => e.scriptId === this.dataSource.find(e => e.id === 0).blockId)
        let selectRadio = triggerBlock.paramsValue.radioSelect.radioType
        switch (selectRadio) {
          case 'dataset':
            triggerType = 'Timed'
            break
          case 'widget':
            triggerType = 'Timed'
            break
          default:
            triggerType = this.botInfo.triggerType
            break
        }
      } catch (error) {
        triggerType = this.botInfo.triggerType
      }
      return triggerType
    },
    clickOther (e) {
      let isOtherArea = true
      let reg = RegExp(/mystyle/)
      e.target.classList.forEach(item => {
        if (reg.test(item)) {
          isOtherArea = false
        }
      })
      if (isOtherArea && document.querySelector('.botart_addblock')) {
        document.querySelector('.botart_addblock').style.display = 'none'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.button_hover:hover {
  cursor: pointer;
  color: $--theme-color !important;
  background-color: $--theme-color-background;
}
.new-bot-design-page {
  height: calc(100% + 32px);
  position: relative;
  .page-content {
    height: 100%;
    .header {
      background-color: #ffffff;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      .header-name {
        font-weight: bold;
        font-size: 20px;
        img {
          width: 40px;
          height: 40px;
        }
      }
    }
    .scroll-css-left {
      width: 380px;
      height: 100%;
      overflow: hidden;
      float: left;
      box-shadow: 1px 0px 0px 0px #f0f0f0;
      padding-right: 20px;
      padding-left: 20px;
      position: relative;
      //&-close-btn {
      //  position: absolute;
      //  top: 10px;
      //  right: 10px;
      //  width: 30px;
      //  height: 30px;
      //  font-size: 14px;
      //  display: flex;
      //  align-items: center;
      //  justify-content: center;
      //  cursor: pointer;
      //  border-radius: 4px;
      //  background-color: #fbfbfb;
      //  &:hover {
      //    background-color: $--theme-color-background;
      //    color: $--theme-color;
      //  }
      //}
    }
    .scroll-css-right {
      height: 100%;
      overflow: hidden;
    }
    .canvas {
      width: 100%;
      height: 100%; // 178 = 50 + 15 + 50 + 10 + 15 + 38
      border-radius: 4px;
      background-color: #fff;
      padding: 10px;
      padding-top: 0;
      padding-right: 20px;
      padding-left: 0;
      &-header {
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
      &-content {
        overflow: auto;
        width: 100%;
        height: 100%;
        background-image: url("../../../../../assets/tile.png");
        background-repeat: repeat;
        background-size: 40px 40px;
        background-color: #fbfbfb;
        position: relative;
        &-scroll {
          min-width: 100%;
          .block {
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: absolute;
            background-color: #fff;
            box-shadow: 0px 0px 8px 0px #f0f0f0;
            border: 1px solid #fcfcfc;
            border-radius: 4px;
            &:hover {
              box-shadow: 0px 0px 8px 0px #f0f0f0;
              border-radius: 2px;
              border: 1px solid #138dc7;
            }
            .block-left {
              width: calc(100% - 35px);
              height: 100%;
            }
            &-icon {
              width: 20px;
              height: 20px;
              border: 1px solid #efefef;
              border-radius: 4px;
              margin-right: 5px;
            }
            .icon-name {
              width: 100%;
              height: 36px;
              line-height: 30px;
              display: flex;
              align-items: center;
              &-value {
                width: calc(100% - 25px);
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
            .icon-note {
              width: 100%;
              padding-left: 25px;
              &-value {
                width: 100%;
                height: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                color: #7f7f7f;
              }
            }
            .block-right {
              height: 100%;
              padding-top: 10px;
              display: flex;
              flex-direction: column;
              align-items: flex-start;
            }
          }
        }
        .new_block_btn {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          > div {
            width: 180px;
            height: 28px;
            background: #f5fcff;
            border-radius: 2px;
            border: 1px dashed #138dc7;
            text-align: center;
            line-height: 28px;
            font-size: 14px;
            color: #138dc7;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            span {
              margin-right: 10px;
            }
          }
        }
        .arcStyle {
          cursor: pointer;
        }
      }
    }
    .limit-content-height {
      height: calc(100% - 50px);
    }
  }
}
.no-permission {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 3em;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 2;
  background: #fff;
}
.el-icon-more {
  font-size: 15px;
  color: #7b7b7b;
  cursor: pointer;
}
.more_operation {
  display: flex;
  .icon_edit,
  .icon_comment_add,
  .icon_delete {
    width: 25px;
    height: 100%;
    font-size: 14px;
  }
}
.action-btn-group {
  display: flex;
}
.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    background-color: $--theme-color-background;
    color: $--theme-color;
  }

  .cuifont {
    font-size: 14px;
    width: 14px;
    height: 14px;
    margin-right: 6px;
  }

  .text {
    font-size: 14px;
    height: 20px;
    line-height: 20px;
  }
}
.close-blank-block {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  &:hover {
    color: $--theme-color;
  }
}
.block_leftgp {
  position: absolute;
  left: 0;
  bottom: 0;
  top: 0;
  ::v-deep .el-tabs {
    height: calc(100% - 80px);
    .el-tabs__content {
      height: calc(100% - 50px);
      .el-tab-pane{
        height: 100%;
      }
    }
  }
}
</style>
